<script lang='ts' setup>
import type {UploadProps, UploadUserFile, ElMessage} from 'element-plus'
import {useFile} from "@/hooks/web/useFile";

const {handlePreview, showViewer, srcList} = useFile()
const {action, headers} = useFile()
const props = defineProps({
  fileType: {default: 'picture'},
  limit: {default: 1}
})

let fileList = ref<UploadUserFile[]>([])


const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  fileList.value = uploadFiles
}

const upload = ref<UploadInstance>()

const handleExceed: UploadProps['onExceed'] = (files) => {
  ElMessage.warning(`文件限制最多只能上传 ${files.length}个`)
}

const handleSuccess = (response) => {
  if (response.code ===  0) {
    let files = [];
    fileList.value.forEach(item => {
      if (item.url) {
        files.push(item)
      }
    })
    fileList.value = files;
    fileList.value.push({
      url: response.data.path,
      name: response.data.name,
      fileId: response.data.file_id,
      file_id: response.data.file_id,
    })
  } else {
    //移出当前文件对象
    ElMessage.error(response.message)
    fileList.value.splice(fileList.value.length - 1, 1)
  }
}

defineExpose({fileList})


</script>
<template>
  <el-upload
      class="upload-demo"
      v-model:file-list="fileList"
      :action="action"
      :on-preview="handlePreview"
      :headers="headers"
      :on-success="handleSuccess"
      :limit="props.limit"
      ref="upload"
      :on-exceed="handleExceed"
      :on-remove="handleRemove"
      :list-type="props.fileType">
    <el-button type="primary" plain>选取文件</el-button>
  </el-upload>
  <el-image-viewer
      v-if="showViewer"
      :z-index="9999"
      @close="()=>{showViewer  =false}"
      :url-list="srcList"
  />
</template>

<style scoped>
.upload-demo {
  width: 200px;
}
</style>